package com.qianying.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qianying.comment.CommonResult;
import com.qianying.entity.SysPermission;
import com.qianying.entity.SysRolePermission;
import com.qianying.mapper.SysPermissionMapper;
import com.qianying.mapper.SysRolePermissionMapper;
import com.qianying.service.SysPermissionService;
import com.qianying.service.SysRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.LinkedHashMap;

@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysRolePermissionService rolePermissionService;

    @Override
    public CommonResult<?> getById(Long id) {
        SysPermission permission = sysPermissionMapper.selectById(id);
        if (permission == null) {
            return CommonResult.failed("没有该记录！");
        }
        return CommonResult.success(permission, "查询成功！");
    }

    @Override
    public CommonResult<?> getByClassNameAndMethodName(String className, String methodName) {
        LambdaQueryWrapper<SysPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermission::getClassName, className)
                .eq(SysPermission::getMethodName, methodName);
        SysPermission permission = sysPermissionMapper.selectOne(queryWrapper);

        if (permission == null) {
            return CommonResult.failed("没有该记录！");
        }
        return CommonResult.success(permission, "查询成功！");
    }

    @Override
    public CommonResult<?> getAllGroupByClassName(Long roleId) {

        // 1. 使用LambdaQueryWrapper构建查询条件（此处查询所有，无过滤条件）
        LambdaQueryWrapper<SysPermission> queryWrapper = new LambdaQueryWrapper<>();
        // 可以添加排序条件，例如按类名和方法名排序
        queryWrapper.orderByAsc(SysPermission::getClassName)
                .orderByAsc(SysPermission::getMethodName);

        // 2. 执行查询，获取所有数据
        List<SysPermission> allPermissions = sysPermissionMapper.selectList(queryWrapper);

        // 3. 按className分组，使用LinkedHashMap保持插入顺序
        Map<String, List<SysPermission>> mapRes = allPermissions.stream()
                .collect(Collectors.groupingBy(
                        SysPermission::getClassName,  // 分组键：类名
                        LinkedHashMap::new,           // 保持顺序的Map实现
                        Collectors.toList()           // 分组值：该类名对应的权限列表
                ));

        if (!mapRes.isEmpty() && roleId != null) {
            //
            CommonResult<Map<String, Boolean>> result = rolePermissionService.getRolePermissionMap();
            if (result.isSuccess()) {
                Map<String, Boolean> keyMap = result.getData();
                mapRes.forEach((className, permissions) -> {
                    // 遍历权限列表
                    permissions.forEach(permission -> {
                        String key = roleId.toString() + "_" + permission.getId();
                        if(keyMap.containsKey(key)){
                            permission.setSelect(true);
                        }
                    });
                });
            }
        }
        // 调用自定义的分组查询方法
        return CommonResult.success(mapRes, "查询成功！");
    }

    /**
     * 保存或更新权限信息
     * 判断依据：相同的类名+方法名+请求路径视为同一记录
     */
    @Override
    public CommonResult<?> saveOrUpdatePermission(SysPermission permission) {
        // 构建查询条件：类名+方法名+请求路径唯一确定一条记录
        LambdaQueryWrapper<SysPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermission::getClassName, permission.getClassName())
                .eq(SysPermission::getMethodName, permission.getMethodName())
                .eq(SysPermission::getRequestMapping, permission.getRequestMapping());

        // 查询是否存在
        SysPermission existing = sysPermissionMapper.selectOne(queryWrapper);

        if (existing != null) {
            // 存在则更新
            if (!StringUtils.isBlank(permission.getName())) {
                existing.setName(permission.getName());
            }
            if (!StringUtils.isBlank(permission.getDescription())) {
                existing.setDescription(permission.getDescription());
            }

            existing.setParentId(permission.getParentId());
            existing.setUpdateTime(LocalDateTime.now());
            if (sysPermissionMapper.updateById(existing) > 0) {
                return CommonResult.success(existing, "更新成功！");
            }
            return CommonResult.failed("更新失败！");
        } else {
            // 不存在则新增
            permission.setCreateTime(LocalDateTime.now());
            permission.setUpdateTime(LocalDateTime.now());
            if (sysPermissionMapper.insert(permission) > 0) {
                return CommonResult.success(permission, "添加成功！");
            }
            return CommonResult.failed("添加失败！");
        }
    }
}

